package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @Author: bowen
 * @Date: 2019/7/22 15:11
 * @Description:
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;

	@Autowired
	RoleDao roleDao;

	@Autowired
	PermissionDao permissionDao;

	@Autowired
	private MenuDao menuDao;

	/**
	 *  @描述：根据用户名获取用户信息
	 */
	public User findByUsername(String username) {
         User user= userDao.findByUsername(username);
         if(ObjectUtils.isEmpty(user)){
         	return null;
         }
		// 根据用户id查询角色信息
		Set<Role> roleList= roleDao.findByUserId(user.getId());
         if(!CollectionUtils.isEmpty(roleList)){
         //	如果角色列表不为空，根据角色id查询权限信息
	       roleList.forEach(role->{
		      Set<Permission> permissionList = permissionDao.findByRoleId(role.getId());
		      role.setPermissions(permissionList);
	       });
	       user.setRoles(roleList);

         }

		return user;
	}


	@Override
	public List<Map> getMenuList(String username) {
		User user = userDao.findByUsername(username);
		Integer id = user.getId();
		Set<Role> roles = roleDao.findByUserId(id);
		Set<Menu> temproal = new HashSet();
		for (Role role : roles) {
			Integer roleId = role.getId();
			Set<Menu> primaryMenuList = roleDao.findMenuByRoleId(roleId);
			temproal.addAll(primaryMenuList);
		}
		List<Menu> result = new ArrayList<>(temproal);
		Collections.sort(result, new Comparator<Menu>() {
			@Override
			public int compare(Menu o1, Menu o2) {
				return o1.getId()-o2.getId();
			}
		});
		List<Map> list = new ArrayList<>();
		for (Menu menu : result) {
			Map map = new HashMap();
			map.put("path", menu.getPath());
			map.put("title", menu.getName());
			map.put("icon", menu.getIcon());
			String path = menu.getPath();
			List<Map> childrens = menuDao.findMenuByParentId(path);
			map.put("children", childrens);
			list.add(map);
		}
		return list;
	}
}
